package org.elepower.controller;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.elepower.dao.UserDao;
import org.elepower.pojo.PsUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/self")
public class SelfController {

    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/update",method = RequestMethod.GET)
    public String  update(HttpSession session) throws Exception{
        PsUser user = (PsUser)session.getAttribute(Constants.LOGIN_USER);
        PsUser psUser = userDao.getUser(user.getId());
        return "system/self/updateInfo";
    }
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> update(PsUser psUser,HttpSession session) throws Exception{
        PsUser user = (PsUser)session.getAttribute(Constants.LOGIN_USER);
        Map<String,Object> map = new HashMap<>();
        //加密
        Md5Hash md5Hash = new Md5Hash(psUser.getPassword(),user.getSalt());
        psUser.setPassword(md5Hash.toString());
        psUser.setLastUpdateTime(new Date());
        //修改
        userDao.updatePassword(psUser);
        map.put("result",true);
        return map;
    }

    @RequestMapping(value = "/md5",method = RequestMethod.POST)
    @ResponseBody
    public String mdg(@RequestParam("oldpassword") String oldpassword, HttpSession session) throws Exception{
        PsUser user = (PsUser)session.getAttribute(Constants.LOGIN_USER);
        Md5Hash md5Hash =new Md5Hash(oldpassword,user.getSalt());
        return md5Hash.toString();
    }
}
